package com.example.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置连接属性
        factory.setHost("59.110.23.211");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("cmlstudy");
        Connection connection = factory.newConnection();
        //3.创建Channel
        Channel channel = connection.createChannel();
        //4.声明队列(可以省略)
        channel.queueDeclare("hello", true, false, false, null);
        //5.消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {//重写handleDelivery方法
            //从队列中收到消息就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            System.out.println("收到消息：" + new String(body));
            }
        };
        channel.basicConsume("hello", true, consumer);
        Thread.sleep(1000);
        //6.释放资源
        //可以只关闭connection，或channel在connection之前先关闭
        channel.close();
        connection.close();

    }
}
